package com.qut.graduate.busrtquery.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.TransitRouteLine;
import com.qingmei2.library.SlideBottomLayout;
import com.qut.graduate.busrtquery.BaseActivity;
import com.qut.graduate.busrtquery.R;
import com.qut.graduate.busrtquery.adapter.BusRouteDetailAdapter;
import com.qut.graduate.busrtquery.bean.RouteStep;
import com.qut.graduate.busrtquery.interfaces.OnItemClickListener;
import com.qut.graduate.busrtquery.utils.common.LogUtils;
import com.qut.graduate.busrtquery.utils.baidumap.BaiduMapUtils;
import com.qut.graduate.busrtquery.utils.baidumap.TransitRouteOverlay;
import com.qut.graduate.busrtquery.utils.uiabout.ScreenUtils;
import com.qut.graduate.busrtquery.utils.uiabout.StatusBarUtils;

import java.util.ArrayList;
import java.util.List;

import am.widget.wraplayout.WrapLayout;

public class BusRouteDetailActivity extends BaseActivity implements View.OnClickListener{
    private static final String TAG = "BusRouteDetailActivity";
    private Context context;
    private MapView mMapView = null;
    private BaiduMap mBaiduMap;
    private RouteLine route = null; // 路线所有信息
    private Overlay mTextOverlay; // 路线详情提示
    private PlanNode stNode; // 路径规划起点
    private PlanNode enNode; // 路径规划终点
    private ArrayList<TransitRouteLine> transitRouteLines; // 传递过来的所有的公交路线
    private int position; // transfer界面点击的recyclerview中的position
    private List<RouteStep> stepList = new ArrayList<RouteStep>();
    private Object step = null;
    private RouteStep routeStep = null;
    private BusRouteDetailAdapter busRouteDetailAdapter;

    private ImageButton mRouteDetailBackImgBtn;
    private SlideBottomLayout mRouteDetailSlideLayout;
    private WrapLayout mRouteDetailWraplayout;
    private TextView mRouteDetailDurDisText;
    private TextView mRouteDetailStationNum;
    private TextView mRouteDetailTransferNum;
    private TextView mRouteDetailUpBusStation;
    private RecyclerView mRouteDetailRecyclerView;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bus_route_detail;
    }

    @Override
    protected void init() {
        this.context = this;
        StatusBarUtils.setStatusBarTransparent(this);
        initView();
        // 获取transfer界面传来的信息
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            position = bundle.getInt("position");
            transitRouteLines = bundle.getParcelableArrayList("transitRouteLines");
            stNode = bundle.getParcelable("stNode");
            enNode = bundle.getParcelable("enNode");
            LogUtils.d("----跳转到公交路线详情界面之后----stNode: " + stNode.getLocation() + "----enNode: " + enNode.getLocation(), getClass());
            initBusRoute(transitRouteLines, position);
        }
        initEvent();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bus_route_detail_back_imgBtn:
                finish();
                break;
        }
    }

    // 通过换乘界面获取的信息设置初始化数据
    private void initEvent() {
        int duration = transitRouteLines.get(position).getDuration(); // 当前路线的计划时间
        int distance = transitRouteLines.get(position).getDistance(); // 当前路线的起终点距离
        double transferDistance = (Math.round(distance / 100d) / 10d); // 换算后的距离
        if (duration / 3600 == 0) {
            mRouteDetailDurDisText.setText(String.valueOf(duration / 60).concat("分钟  ").
                    concat(String.valueOf(transferDistance)).concat("公里"));
        } else {
            mRouteDetailDurDisText.setText(String.valueOf(duration / 3600).concat("小时").
                    concat(String.valueOf((duration % 3600) / 60)).concat("分钟  ").
                    concat(String.valueOf(transferDistance)).concat("公里"));
        }

        int stationNum = 0; // 站数
        String upBusStation = null; // 上车地点的公交站名
        String instructionsBeSub;  // 被截取的详细路径规划变量
        String instructionsSaveSub; // 存放被截取具体信息(公交线路名、地铁线路名、总站数等)的而声明的详细路径规划变量
        String instructionsForStationNum; // 为了统计站点数 stationNum 而声明的详细路径规划变量
        TransitRouteLine.TransitStep stepForComputeStepType = null; // 通过它统计路线公交、地铁、步行的步骤
        TransitRouteLine.TransitStep stepForComputeStationNum = null; // 通过它计算总的站点数
        List<String> listBus = new ArrayList<>(); // 存放某段公交路径规划详情
        List<String> listWalk = new ArrayList<>(); // 存放某段步行路径规划详情

        stepForComputeStepType = transitRouteLines.get(position).getAllStep().get(0);
        instructionsBeSub = stepForComputeStepType.getInstructions();
        if (instructionsBeSub.contains("到达") && instructionsBeSub.contains("站")) {
            upBusStation = instructionsBeSub.substring(instructionsBeSub.indexOf("达") + 1, instructionsBeSub.indexOf("站") + 1);
        }
        for (int i = 0; i < transitRouteLines.get(position).getAllStep().size(); i++) {
            stepForComputeStepType = transitRouteLines.get(position).getAllStep().get(i);
            instructionsBeSub = stepForComputeStepType.getInstructions();
            Log.w("规划详情:", instructionsBeSub);
            if (stepForComputeStepType.getStepType() != TransitRouteLine.TransitStep.TransitRouteStepType.WAKLING) {
                if (instructionsBeSub.contains("地铁")) {
                    instructionsSaveSub = instructionsBeSub.substring(instructionsBeSub.indexOf("地"), instructionsBeSub.indexOf("线") + 1);
                    listBus.add(instructionsSaveSub);
                } else if (instructionsBeSub.contains("路")) {
                    instructionsSaveSub = instructionsBeSub.substring(instructionsBeSub.indexOf("坐") + 1, instructionsBeSub.indexOf("路") + 1);
                    listBus.add(instructionsSaveSub);
                } else if (instructionsBeSub.contains("大站车")) {
                    instructionsSaveSub = instructionsBeSub.substring(instructionsBeSub.indexOf("坐") + 1, instructionsBeSub.indexOf("车") + 1);
                    listBus.add(instructionsSaveSub);
                } else {
                    instructionsSaveSub = instructionsBeSub.substring(instructionsBeSub.indexOf("坐") + 1, instructionsBeSub.indexOf(","));
                    listBus.add(instructionsSaveSub);
                }
            } else {
                if (instructionsBeSub.contains(",")) {
                    instructionsSaveSub = instructionsBeSub.substring(0, instructionsBeSub.indexOf(","));
                    listWalk.add(instructionsSaveSub);
                }
            }
        }
        for (int i = 0; i < transitRouteLines.get(position).getAllStep().size(); i++) {
            stepForComputeStationNum = transitRouteLines.get(position).getAllStep().get(i);
            instructionsForStationNum = stepForComputeStationNum.getInstructions();
            if (stepForComputeStationNum.getStepType() != TransitRouteLine.TransitStep.TransitRouteStepType.WAKLING) {
                if (instructionsForStationNum.contains("地铁")) {
                    instructionsSaveSub = instructionsForStationNum.substring(instructionsForStationNum.indexOf("过") + 1);
                    if (instructionsSaveSub.contains("站")) {
                        instructionsSaveSub = instructionsSaveSub.substring(0, instructionsSaveSub.indexOf("站"));
                        stationNum += Integer.parseInt(instructionsSaveSub);
                    } else {
                        stationNum += Integer.parseInt(instructionsSaveSub);
                    }
                } else if (instructionsForStationNum.contains("路")) {
                    instructionsSaveSub = instructionsForStationNum.substring(instructionsForStationNum.indexOf("过") + 1);
                    if (instructionsSaveSub.contains("站")) {
                        instructionsSaveSub = instructionsSaveSub.substring(0, instructionsSaveSub.indexOf("站"));
                        stationNum += Integer.parseInt(instructionsSaveSub);
                    } else {
                        stationNum += Integer.parseInt(instructionsSaveSub);
                    }
                }
            }
        }
        mRouteDetailStationNum.setText(String.valueOf(stationNum).concat("站"));
        mRouteDetailUpBusStation.setText(upBusStation + "上车");
        if (listBus.size() - 1 > 0)
            mRouteDetailTransferNum.setText("换乘" + String.valueOf(listBus.size() - 1) + "次");
        else mRouteDetailTransferNum.setText("");

        for (int i = 0; i < listBus.size(); i++) {
            if (i > 0) {
                ImageView imageView = new ImageView(context);
                imageView.setImageResource(R.mipmap.icon_transfer);
                imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
                params.height = ScreenUtils.dp2px(20);
                params.width = ScreenUtils.dp2px(20);
                params.setMargins(ScreenUtils.dp2px(10), 5, 0, 5);
                imageView.setLayoutParams(params);
                mRouteDetailWraplayout.addView(imageView);
            }
            ImageView imageView = new ImageView(context);
            if (listBus.get(i).contains("地铁")) imageView.setImageResource(R.mipmap.icon_subway);
            else imageView.setImageResource(R.mipmap.icon_bus);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
            params.height = ScreenUtils.dp2px(20);
            params.width = ScreenUtils.dp2px(20);
            params.setMargins(0, 5, 0, 5);
            imageView.setLayoutParams(params);
            mRouteDetailWraplayout.addView(imageView);

            TextView showText = new TextView(context);
            showText.setTextColor(Color.BLACK);
            showText.setTextSize(14);
            showText.setText(listBus.get(i));
            LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
            params1.setMargins(0, 5, 0, 5);
            showText.setLayoutParams(params1);
            mRouteDetailWraplayout.addView(showText);
        }
    }

    public void initView() {
        mMapView = findViewById(R.id.bus_route_detail_mapView);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setViewPadding(ScreenUtils.dp2px(10), 0, 0, ScreenUtils.dp2px(60));
        mRouteDetailBackImgBtn = findViewById(R.id.bus_route_detail_back_imgBtn);
        mRouteDetailSlideLayout = findViewById(R.id.bus_route_detail_slideLayout);
        mRouteDetailWraplayout = findViewById(R.id.bus_route_detail_wrapLayout);
        mRouteDetailDurDisText = findViewById(R.id.bus_route_detail_dur_dis_text);
        mRouteDetailStationNum = findViewById(R.id.bus_route_detail_station_num);
        mRouteDetailTransferNum = findViewById(R.id.bus_route_detail_transfer_num);
        mRouteDetailUpBusStation = findViewById(R.id.bus_route_detail_upBus_station);
        mRouteDetailRecyclerView = findViewById(R.id.bus_route_detail_recyclerView);

        mRouteDetailBackImgBtn.setOnClickListener(this);
    }

    /**
     * 将传过来的路线详情展示到recyclerview中
     *
     * @param transitRouteLines
     * @param position
     */
    public void initBusRoute(ArrayList<TransitRouteLine> transitRouteLines, int position) {
        route = transitRouteLines.get(position);
        stepList.clear();
        TransitRouteOverlay overlay = new TransitRouteOverlay(mBaiduMap);
        overlay.setData((TransitRouteLine) route);
        mBaiduMap.setOnMarkerClickListener(overlay);
        overlay.addToMap();
        overlay.zoomToSpan();

        for (int i = 0; i < route.getAllStep().size(); i++) {
            step = route.getAllStep().get(i);
            routeStep = new RouteStep();
            String string = ((TransitRouteLine.TransitStep) step).getInstructions();
            LatLng latLng = ((TransitRouteLine.TransitStep) step).getEntrance().getLocation();
            Log.w("路段详情:", string);
            routeStep.setNodeLocation(latLng);
            routeStep.setNodeTitle(string);
            stepList.add(routeStep);
        }
        if (stepList.size() > 0) {
            mRouteDetailRecyclerView.setLayoutManager(new LinearLayoutManager(context));
            busRouteDetailAdapter = new BusRouteDetailAdapter(stepList, this);
            mRouteDetailRecyclerView.setAdapter(busRouteDetailAdapter);
            busRouteDetailAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onClick(View view, int position) {
                    if (mTextOverlay != null) {
                        mTextOverlay.remove();
                    }
                    if (position == 0) {
                        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(stNode.getLocation()));
                    } else if (position == stepList.size() + 1) {
                        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(enNode.getLocation()));
                    } else if (position >= 1 && position < stepList.size()) {
                        BaiduMapUtils.moveToLatLngBoundsBuilder(mBaiduMap, stepList.get(position - 1).getNodeLocation(), stepList.get(position).getNodeLocation());
                        String title = stepList.get(position - 1).getNodeTitle();
                        if (position % 2 == 1) {
                            if (title.contains(","))
                                title = title.substring(0, title.indexOf(","));
                        } else {
                            title = title.substring(title.indexOf("坐") + 1, title.indexOf(","));
                        }
                        mTextOverlay = BaiduMapUtils.addTextOverLayOnRoute(mBaiduMap,stepList.get(position - 1).getNodeLocation(),
                                stepList.get(position).getNodeLocation(), title);
                        LogUtils.d("----TransitRouteOverlay addTextOverLayOnRoute：" + stepList.get(position).getNodeLocation().latitude + "  "
                                + stepList.get(position).getNodeLocation().longitude  + "  " + stepList.get(position - 1).getNodeLocation().latitude + "  "
                                + stepList.get(position - 1).getNodeLocation().longitude);
                    } else if (position == stepList.size()) {
                        BaiduMapUtils.moveToLatLngBoundsBuilder(mBaiduMap, stepList.get(position - 1).getNodeLocation(), enNode.getLocation());
                        String title = stepList.get(position - 1).getNodeTitle();
                        if (title.contains(",")) {
                            title = title.substring(0, title.indexOf(","));
                        }
                        mTextOverlay = BaiduMapUtils.addTextOverLayOnRoute(mBaiduMap,stepList.get(position - 1).getNodeLocation(),
                                enNode.getLocation(), title);
                    }
                    mRouteDetailSlideLayout.hide();
                }
            });
            busRouteDetailAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

}
